﻿using System;
using System.Diagnostics.Contracts;
using System.Reflection;
using NHibernate.Cfg;
using System.Linq;

namespace OpenWaves.ActivityFeed.NHibernate
{
    public static class ConfigurationExtensions
    {
        public static Configuration AddConstraints(this Configuration configuration)
        {
            return configuration.AddFromEmbeddedResource("constraints.hbm.xml");
        }

        public static Configuration AddIndexes(this Configuration configuration)
        {
            return configuration.AddFromEmbeddedResource("indexes.hbm.xml");
        }

        private static Configuration AddFromEmbeddedResource(this Configuration configuration, string resourceName)
        {
            var resourceFullName = String.Concat(typeof(UpdateMap).Assembly.GetName().Name, ".", resourceName);
            var assembly = Assembly.GetExecutingAssembly();

            Contract.Assert(
                assembly.GetManifestResourceNames().FirstOrDefault(
                    r => string.Compare(r, resourceFullName, StringComparison.InvariantCultureIgnoreCase) == 0) != null,
                "Cannot find resource file: " + resourceFullName);
            
            using (var resourceStream = assembly.GetManifestResourceStream(resourceFullName))
            {
                configuration.AddInputStream(resourceStream);
            }
            return configuration;
        }
    }
}